package com.hyx.java.base;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.json.JSONUtil;
import com.hyx.java.constant.HyxConstant;
import com.hyx.java.entity.HyxAdmin;
import com.hyx.java.entity.HyxUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Controller
public class BaseCtrl {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void setCache(String key, String value){
        redisTemplate.opsForValue().set(key, value, 2, TimeUnit.HOURS);
    }

    public String getCache(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public void delCache(){
        String token = request.getHeader(HyxConstant.LOGIN_TOKEN_KEY);
        redisTemplate.delete(token);
    }

    public HyxUser getUser(){
        String token = request.getHeader(HyxConstant.LOGIN_TOKEN_KEY);
        return JSONUtil.toBean(getCache(token), HyxUser.class);
    }

    public HyxAdmin getAdmin(){
        String token = request.getHeader(HyxConstant.LOGIN_TOKEN_KEY);
        return JSONUtil.toBean(getCache(token), HyxAdmin.class);
    }
}
